<?
  session_start();
  if(isset($_SESSION['loginerror'])) $loginerror = $_SESSION['loginerror'];
  if(!isset($_SESSION['validuser'])){
    print $loginerror;
    print "<form method='post' action='verifyuser.php'>";
    print "<table id='loginform' style='margin: 50px auto 0 auto'>";
    print "<tr><th>Username:</td><td><input type='text' name='uname'></td></tr>";
    print "<tr><th>Password:</td><td><input type='password' name='pword'></td></tr>";
    print "<tr><th colspan='2'><button type='submit'>Login</button></td></tr>";
    print "</table>";
    print "</form>";
    exit();
  }
?>

<script src="//code.jquery.com/jquery-1.11.0.min.js"></script>
<script src="//code.jquery.com/ui/1.10.4/jquery-ui.js"></script>
<script src="fileupload/jquery.fileupload.js"></script>

<?php
  // Fill These In!
  $bucket = "rdp-music";
  $accesskey = "AKIAJIZQG4MAPIGZRPCA";
  $secret = "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";
  $key = uniqid() . ".mp3";

  $now = strtotime(date("Y-m-d\TG:i:s"));
  $expire = date('Y-m-d\TG:i:s\Z', strtotime('+ 10 hours', $now)); // credentials valid 10 minutes from now

  $policy = '{
              "expiration": "' . $expire . '",
              "conditions": [
                  {
                      "bucket": "' . $bucket . '"
                  },
                  {
                      "acl": "public-read"
                  },
                  [
                      "starts-with",
                      "$key",
                      ""
                  ],
                  {
                      "success_action_status": "201"
                  },
                  [
                    "starts-with",
                    "$Content-Type",
                    ""
                  ]
              ]
          }';

  $base64Policy = base64_encode($policy);
  $signature = base64_encode(hash_hmac("sha1", $base64Policy, $secret, $raw_output = true));
?>

<style>
  .progress {
      position: relative;
      width: 300px;
      height: 15px;
      background: #C7DA9F;
      border-radius: 10px;
      overflow: hidden;
      display: none;
  }

  .bar {
      position: absolute;
      top: 0;
      left: 0;
      width: 0;
      height: 15px;
      background: #85C220;
  }
</style>

<form action="//s3.amazonaws.com/<?php echo $bucket; ?>/" method="POST" enctype="multipart/form-data" class="direct-upload">

    <!-- We'll specify these variables with PHP -->
    <!-- Note: Order of these is Important -->
    <input type="hidden" name="key" value="<?= $key; ?>">
    <input type="hidden" name="AWSAccessKeyId" value="<?php echo $accesskey; ?>">
    <input type="hidden" name="acl" value="public-read">
    <input type="hidden" name="success_action_status" value="201">
    <input type="hidden" name="policy" value="<?php echo $base64Policy; ?>">
    <input type="hidden" name="signature" value="<?php echo $signature; ?>">
    <input type="hidden" name="Content-Type" value="audio/mpeg">

    Select File: <input type="file" name="file" />

    <!-- Progress Bar to show upload completion percentage -->
    <div class="progress"><div class="bar"></div></div>

</form>

<style>
  table{
    border-collapse: collapse;
  }

  td, th{
    padding: 5px 5px 10px 5px;
    vertical-align: top;
  }

  th{
    text-align: right;
  }

  td{
    text-align: left;
  }

  input, textarea{
    width: 500px;
  }

  #duration{
    width: auto;
  }

  #detail_form{
    display: none;
  }
</style>

<!-- Used to Track Upload within our App -->
<form action="process-form-data.php" method="POST" id="detail_form">
  <input type="hidden" name="filename" id="upload_original_name" value="<?= $key; ?>">
  <table>
    <tr>
      <th>Title:</th>
      <td><input type="text" name="title" id="upload_custom_name"></td>
    </tr>
    <tr>
      <th>Duration (Seconds):</th>
      <td><input type="text" name="duration" id="duration" width="5" maxlength="5"></td>
    </tr>
    <tr>
      <th>Description:</th>
      <td><textarea rows="10" name="desc"></textarea></td>
    </tr>
    <tr>
      <th colspan="2">
        <button type="submit" onclick="window.onbeforeunload = null;">Continue</button>
      </th>
    </tr>
  </table>
</form>

<script>
  var uploadSuccess = true;
  $(document).ready( function() {
    $('.direct-upload').each( function() {
      var form = $(this);

      form.fileupload({
        url: form.attr('action'),
        type: 'POST',
        datatype: 'xml',
        add: function (event, data) {
          $(".progress").show();
          // Message on unLoad.
          window.onbeforeunload = function() {
            return 'You have unsaved changes.';
          };

          // Submit
          data.submit();
        },
        send: function(e, data) {
          // onSend
        },
        progress: function(e, data){
          // This is what makes everything really cool, thanks to that callback
          // you can now update the progress bar based on the upload progress.
          var percent = Math.round((data.loaded / data.total) * 100);
          $('.bar').css('width', percent + '%');
        },
        fail: function(e, data) {
          console.log(e);
          console.log(data);
          alert("Upload fail");
          $(".progress").hide();
          uploadSuccess = false;
          // Remove 'unsaved changes' message.
          window.onbeforeunload = null;
        },
        success: function(data) {
            // onSuccess
        },
        done: function (event, data) {
          console.log(data);
          if(uploadSuccess){
            // Fill the name field with the file's name.
            $('#upload_custom_name').val(data.originalFiles[0].name);
            $("#detail_form").show();
            $(".direct-upload").hide();
          }
        },
      });
    });
  });
</script>